<?php

namespace app\user\controller\user;

use app\admin\logic\ExportQuestionLogic;
use app\admin\logic\ImportQuestionLogic;
use app\admin\model\Coursequestioncategory;
use app\common\controller\Userend;
use app\common\exception\BusinessException;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 导入题目任务
 * @icon fa fa-circle-o
 */
class Importquestiontask extends Userend
{

    /**
     * 模型对象
     * @var \app\admin\model\Importquestion
     */
    protected $model = null;

    /**
     * 是否是关联查询
     */
    protected $relationSearch = true;

    /**
     * 数据限制字段
     */
    protected $dataLimitField = 'uid';

    /**
     * 是否开启数据限制
     * 支持auth/personal
     * 表示按权限判断/仅限个人
     * 默认为禁用,若启用请务必保证表中存在user_id字段
     */
    protected $dataLimit = true;

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Importquestion;
    }

    /**
     * 任务列表
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['course', 'paper'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        $userInfo = $this->auth->getUserinfo();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    if (empty($params['course_id'])) {
                        throw new BusinessException('请选择关联课程');
                    }
                    if (empty($params['category_id'])) {
                        throw new BusinessException('请选择关联分类');
                    }
                    $params['create_time'] = time();
                    $params['update_time'] = time();
                    $params['uid'] = $userInfo['user_id'];
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $userInfo = $this->auth->getUserinfo();
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['uid'] != $userInfo['user_id']) {
            $this->error(__('您无权限编辑此试卷'));
        }
        $adminIds = $this->getDataLimitUserIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        $this->view->assign("categoryParams", 'data-params={"custom[course_id]":["eq","' . $row['course_id'] . '"]}');
        return $this->view->fetch();
    }

    /**
     * 导入题目
     */
    public function importQuestion($ids = null)
    {
        $userInfo = $this->auth->getUserinfo();
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['uid'] != $userInfo['user_id']) {
            $this->error(__('您无权限导入到此试卷'));
        }
        if ($this->request->isPost()) {
            // 请求参数
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('请求参数不得为空'));
            }
            if (empty($params['paper_id'])) {
                $this->error(__('导入试卷不得为空'));
            }
            if (empty($params['attachment'])) {
                $this->error(__('请求文件不得为空'));
            }
            try {
                Db::startTrans();
                (new ImportQuestionLogic())->import($row['course_id'], $params['paper_id'], $params['attachment'], $userInfo['user_id']);
                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                $this->error(__($exception->getMessage()));
            }
            $this->success('导入成功');
        }
        $this->assign('ids', $ids);
        return $this->view->fetch();
    }

    /**
     * AI导题
     */
    public function aiimportquestion($ids = null)
    {
        $userInfo = $this->auth->getUserinfo();
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['uid'] != $userInfo['user_id']) {
            $this->error(__('您无权限导入到此试卷'));
        }
        if ($this->request->isPost()) {
            // 请求参数
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('请求参数不得为空'));
            }
            if (empty($params['paper_id'])) {
                $this->error(__('导入试卷不得为空'));
            }
            if (empty($params['attachment'])) {
                $this->error(__('请求文件不得为空'));
            }
            try {
                Db::startTrans();
                $time = time();
                $importModel = new \app\admin\model\Importquestion;
                $saveData = [
                    'app_id' => $userInfo['app_id'],
                    'course_id' => $row['course_id'],
                    'paper_id' => $row['id'],
                    'file_type' => 20,
                    'file_path' => cdnurl($params['attachment'],true),
                    'create_time' => $time,
                    'update_time' => $time,
                ];
                $importModel->save($saveData);
                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                $this->error(__($exception->getMessage()));
            }
            $this->success('申请成功，请注意关注任务进度');
        }
        $this->assign('ids', $ids);
        return $this->view->fetch();
    }

    /**
     * 导出题目
     * @param $ids
     * @return string
     * @throws \think\Exception
     */
    public function exportquestion($ids = null)
    {
        $userInfo = $this->auth->getUserinfo();
        if ($this->request->isPost()) {
            // 请求参数
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('请求参数不得为空'));
            }
            if (empty($params['paper_id'])) {
                $this->error(__('导出试卷不得为空'));
            }

            // 查询试卷
            $row = $this->model->get($ids);
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            if ($row['uid'] != $userInfo['user_id']) {
                $this->error(__('您无权限导出此试卷'));
            }
            try {
                $filePath = (new ExportQuestionLogic())->export([$row['course_id']], [$params['paper_id']]);
            } catch (\Exception $exception) {
                $this->error(__($exception->getMessage()));
            }
            $this->success('导出成功', null, $filePath);
        }
        $this->assign('ids', $ids);
        return $this->view->fetch();
    }

    /**
     * 删除试卷
     */
    public function del($ids = "")
    {
        $userInfo = $this->auth->getUserinfo();
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitUserIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    if ($v['uid'] != $userInfo['user_id']) {
                        $this->error(__("试卷:" . $v['name'] . '您无权限删除'));
                    }
                    $count += $v->delete();
                }

                // 同步删除题目
                $where = ['extend_id' => ['in', $ids], 'uid' => ['=', $userInfo['user_id']]];
                $model = new \app\admin\model\Question();
                $model->where($where)->delete();
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 批量更新
     */
    public function multi($ids = "")
    {
        $userInfo = $this->auth->getUserinfo();
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $action = $this->request->post("action");
        if ($ids) {
            if ($action == 'clearquestion') {

                // 查询全部试卷
                $allPaper = $this->model->where(['id' => ['in', $ids], 'uid' => ['=', $userInfo['user_id']]])->select();

                // 循环试卷
                $allCourseId = [];
                foreach ($allPaper as $paper) {
                    // 保存全部课程编号
                    $allCourseId[] = $paper['course_id'];

                    // 删除试卷中的题目
                    $where = [
                        'extend_id' => ['=', $paper['id']],
                        'uid' => ['=', $userInfo['user_id']]
                    ];
                    $model = new \app\admin\model\Question();
                    $model->where($where)->delete();
                }

                // 循环处理课程分类的题目数量
                $questionCategoryModel = new Coursequestioncategory();
                foreach ($allCourseId as $course_id) {
                    $questionCategoryList = $questionCategoryModel->where(['course_id' => $course_id, 'level' => 1])->select();
                    // 循环处理分类
                    foreach ($questionCategoryList as $value) {
                        $questionCategoryModel->updateCateGoryAndPaper($course_id, $value['id']);
                    }
                }
            }
        }
        $this->success();
    }
}
